const xss = require('xss')
const { exec, escape } = require('../db/mysql');

const getList = (author, keyword) => {
  author = escape(author)
  keyword = escape('%' + keyword + '%')

  let sql = `select * from blogs where 1=1 `;
  if(author != "''") {     // 注意不是 if(author)。
    sql += `and author=${author} `
  }
  if(keyword) {
    sql += `and title like ${keyword} `
  }
  sql += `order by createtime desc`;
  // console.log('sql注入是', sql)
  // 返回promise
  return exec(sql);
}

const getDetail = (id) => {
  id = escape(id)

  const sql = `select * from blogs where id=${id}`
  return exec(sql).then(rows => {
    return rows[0]
  })
}

const newBlog = (blogData = {}) => {
  // param = _ 的写法，表示param如果不存在，就使用 _ 做兜底。
  // blogData 是一个博客对象，包含 title content author 属性
  let title = xss(blogData.title);
  let content = xss(blogData.content);
  let author = blogData.author;
  const createtime = Date.now();

  title = escape(title)
  content = escape(content)
  author = escape(author)
  let sql = `
    insert into blogs (title, content, createtime, author) 
    values (${title}, ${content}, '${createtime}', ${author})
  `
  return exec(sql).then(insertData => {
    return {
      id: insertData.insertId
    }
  })
};

const updateBlog = (id, blogData = {}) => {
  // id 就是要更新博客的 id
  // blogData 是一个博客对象，包含 title content 属性
  let title = xss(blogData.title)
  let content = xss(blogData.content)

  id = escape(id)
  title = escape(title)
  content = escape(content)
  let sql = `
    update blogs set title=${title}, content=${content} where id=${id}
  ` 
  return exec(sql).then(updateData => {
    if(updateData.affectedRows > 0) {
      return true
    } else {
      return false
    }
  })


  return true;
}

const delBlog = (id, author) => {
  id = escape(id)
  author = escape(author)
  // id 就是要删除博客的 id
  const sql = `
    delete from blogs where id=${id} and author=${author}
  `
  return exec(sql).then(delData => {
    if(delData.affectedRows > 0) {
      return true
    } else {
      return false
    }
  })
}

module.exports = {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  delBlog
}